package com.example.experiment3.controller;

import com.example.experiment3.service.MyService;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
@Controller
public class MyController  {
    @Autowired
    MyService myService;

   public static List<CSVRecord> records=null;

    @RequestMapping ("/api")
    @ResponseBody
    public String getFoos(@RequestParam String id) {
        return "ID: " + id;
    }


    @RequestMapping("/data")
    @ResponseBody
    public  HashMap<String, Object> DataCos(@RequestParam("country") String coty, HttpServletResponse response) {
        System.out.println("entry data");
        System.out.println("cpty:"+coty);
        HashMap<String, Object>maps = new HashMap<String, Object>();
        int newWorldCount = 0;
        int newCotyCount = 0;
        int oldWorldCount = 0;
        int oldCotyCount = 0;
        HashMap<String, Object> citys = new HashMap<String, Object>();
        System.out.println("records"+records);
        System.out.println("records"+MyController.records);
        List<CSVRecord> record1=MyController.records.subList(0,records.size());
        for (CSVRecord record : record1) {
            newWorldCount = newWorldCount + Integer.parseInt(record.get(record.size() - 1));
            oldWorldCount=oldWorldCount+Integer.parseInt(record.get(record.size() - 2));
            if(record.get("Country/Region").equalsIgnoreCase(coty)){
                newCotyCount=newCotyCount+ Integer.parseInt(record.get(record.size() - 1));
                oldCotyCount=oldCotyCount+Integer.parseInt(record.get(record.size() - 2));
                  if(record.get("Province/State")!=null){
                      citys.put(record.get("Province/State"),Integer.parseInt(record.get(record.size() - 1)));
                  }
            }
        }
        if(citys.isEmpty()){
            citys.put("coty",newWorldCount);
        }
        maps.put("newWorldCount",newWorldCount);
        maps.put("newCotyCount",newCotyCount);
        maps.put("addWorldCount",newWorldCount-oldWorldCount);
        maps.put("addCotyCount",newCotyCount-oldCotyCount);
        maps.put("citys",citys);

        //在使用axios请求的时候,返回的响应中一定要有下面的请求头
       response.setHeader("Access-Control-Allow-Origin", "*");
       response.setHeader("Cache-Control","no-cache");
        return maps;
    }

}
